//index.js
//获取应用实例
const app = getApp()
const db = wx.cloud.database()
Component({
  data: {
    first:1,  //第一次加载页面,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    TabCur: 0,
    MainCur:0,
    scrollLeft: 0,
    list:[],
    list2:[],
    id_index:{'书':0,'衣物':1,'食品':2,'其他':3},
    id_list:[{name:"书",id:0},{name:"衣物",id:1},{name:"食品",id:2},{name:"其他",id:3}],
    keyword:'',
    category: ['书','衣物','食品','其他'],
    load:true,
    VerticalNavTop:''
  },
    options: {
        addGlobalClass: true,
        test:'',
        CustomBar:app.globalData.CustomBar
    },
attached:function(){
    wx.showLoading({
        title: '加载中',
      })
            // 获取商品列表
            // this.getCommodity();
            wx.cloud.database().collection('yw_commodity').watch({
                onChange:res=>{
                    // if(this.data.first==1){
                    //     this.setData({
                    //         first:2
                    //     })
                    // }else{
                        this.getCommodity();
                    // }
                },
                onError:err=>{
                    console.log(err)
                }
            })
        },

  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
methods:{
    VerticalMain(e) {
        let that = this;
        let list = this.data.id_list;
        let tabHeight = 0;
        // console.log(list)
        if (this.data.load) {
          for (let i = 0; i < list.length; i++) {
            let view = this.createSelectorQuery().select("#main-"+list[i].id);
            view.fields({
              size: true
            }, data => {
              list[i].top = tabHeight;
              tabHeight = tabHeight + data.height;
              list[i].bottom = tabHeight;     
            }).exec();
          }
          that.setData({
            load: false,
            id_list: list
          })
        }
        let scrollTop = e.detail.scrollTop + 20;
        for (let i = 0; i < list.length; i++) {
          if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
            that.setData({
              VerticalNavTop: (list[i].id - 1) * 50,
              TabCur: list[i].id
            })
            return false
          }
        }
      },
    getCommodity(){
    
        let p =0
        this.setData({
            list2:[]
        })
        this.data.category.forEach((item,index)=>{
            console.log(this.data.id_index[item])
        wx.cloud.database().collection('yw_commodity').where({category:item,status:'normal'}).limit(4).get().then((res)=>{
            // console.log(res)
            let data = res.data
            let newData={}
            let n =0,m=0
                // console.log(data)
            data.map((e,i,a)=>{
                // console.log(e)
                    m++
                    if(Boolean(e.picture.length)){
                        wx.cloud.getTempFileURL({
                            fileList:[
                                e.picture[0],
                            ]
                        }).then(res=>{
                                e.img=res.fileList[0].tempFileURL
                                if(!newData.hasOwnProperty(e.category)){
                                    newData[e.category]=[]
                                    newData['sx']=this.data.id_index[item]
                                    newData[e.category].push(e)
                                }else{
                                newData[e.category].push(e)
                                }
                                n++;
                                if(m==n){
                                    wx.hideLoading()
                                    let list = this.data.list2.concat(newData)
                                    list = list.sort((a,b)=>{
                                        return a.sx-b.sx
                                    })
                                    let list3 = {}
                                     Object.keys(list).map(key=>{
                                        Object.assign(list3,list[key])
                                    })
                                    delete list3.sx
                                    this.setData({
                                        list:list3
                                    })
                                    this.setData({
                                        list2:this.data.list2.concat(newData)
                                    })

                                }
                        })
                    }else{
                        // 暂无图片
                        e.img='https://bkimg.cdn.bcebos.com/pic/42166d224f4a20a4fd5775e193529822720ed04f?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg'
                        if(!newData.hasOwnProperty(e.category)){
                            newData[e.category]=[]
                            newData['sx']=this.data.id_index[item]
                            newData[e.category].push(e)
                        }else{
                        newData[e.category].push(e)
                        }
                        n++
                        if(m==n){
                            wx.hideLoading()
                            let list = this.data.list2.concat(newData)
                            list = list.sort((a,b)=>{
                                return a.sx-b.sx
                            })
                            let list3 = {}
                             Object.keys(list).map(key=>{
                                Object.assign(list3,list[key])
                            })
                            delete list3.sx
                            this.setData({
                                list:list3
                            })
                            this.setData({
                                list2:this.data.list2.concat(newData)
                            })
                        }
                            // this.setData({
                            //     list:newData
                            // })
                            // this.setData({
                            //     list2:newData
                            // })
                    }
            })
        
        })

        })
    },
    gw: function(e){
        if(app.globalData.auth){
            wx.navigateTo({
                url: '../gc/commodity/commodity?id='+e.currentTarget.dataset.id+'&title='+e.currentTarget.dataset.title
            })
        }else{
            wx.showToast({
              title: '您还未授权！',
              icon:'error'
            })
        }
    },
    search:function(){
      let keyword=this.data.keyword
      let _ = db.command
      if(keyword==''){
          this.getCommodity
      }else{
        this.setData({
            list2:[]
        })
      this.data.category.forEach((item,index)=>{
      db.collection("yw_commodity").where(
          _.and([
            {category:item},
            {status:'normal'},
          _.or([
            { 
              methods:{
                  $regex:'/.*'+keyword+'.*/',
                  $options: 'i'
              },
            },
            {
              category_school:{
                  $regex:'.*'+keyword+'.*',
                  $options: 'i'
              },
            },
            {
              name:{
                  $regex:'.*'+keyword+'.*',
                  $options: 'i'
              },
            },
            {
              except:{
                  $regex:'.*'+keyword+'.*',
                  $options: 'i'
              },
            }
        ])
          ]
          ),
      ).get().then(res=>{
          console.log(res.data)
        let data = res.data
        let newData={}
        let n =0,m=0
            // console.log(data)
        data.map((e,i,a)=>{
            // console.log(e)
                m++
                if(Boolean(e.picture.length)){
                    wx.cloud.getTempFileURL({
                        fileList:[
                            e.picture[0],
                        ]
                    }).then(res=>{
                            e.img=res.fileList[0].tempFileURL
                            if(!newData.hasOwnProperty(e.category)){
                                newData[e.category]=[]
                                newData['sx']=this.data.id_index[item]
                                newData[e.category].push(e)
                                // let ls2 = this.data.id_index
                                // ls2[e.category]=p
                                // console.log(ls2)
                                // this.setData({
                                //     id_index:ls2
                                // })
                                // p++
                            }else{
                            newData[e.category].push(e)
                            }
                            n++;
                            if(m==n){
                                wx.hideLoading()
                                let list = this.data.list2.concat(newData)
                                // console.log(list)
                                list = list.sort((a,b)=>{
                                    return a.sx-b.sx
                                })
                                // console.log(list)
                                let list3 = {}
                                 Object.keys(list).map(key=>{
                                    Object.assign(list3,list[key])
                                })
                                delete list3.sx
                                this.setData({
                                    list:list3
                                })
                                this.setData({
                                    list2:this.data.list2.concat(newData)
                                })
                            }
                    })
                }else{
                    // 暂无图片
                    e.img='https://bkimg.cdn.bcebos.com/pic/42166d224f4a20a4fd5775e193529822720ed04f?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg'
                    if(!newData.hasOwnProperty(e.category)){
                        // let ls2 = this.data.id_index
                        // ls2[e.category]=p
                        // this.setData({
                            // id_index:ls2
                        // })
                        // p++
                        newData[e.category]=[]
                        newData['sx']=this.data.id_index[item]
                        newData[e.category].push(e)
                    }else{
                    newData[e.category].push(e)
                    }
                    n++
                    if(m==n){
                        wx.hideLoading()
                        let list = this.data.list2.concat(newData)
                        list = list.sort((a,b)=>{
                            return a.sx-b.sx
                        })
                        let list3 = {}
                         Object.keys(list).map(key=>{
                            Object.assign(list3,list[key])
                        })
                        delete list3.sx
                        this.setData({
                            list:list3
                        })
                        this.setData({
                            list2:this.data.list2.concat(newData)
                        })
                    }
                        // this.setData({
                        //     list:newData
                        // })
                        // this.setData({
                        //     list2:newData
                        // })
                }
        })
    
      })
    })
      }
    },
    InputBlur(e){
        this.setData({
            keyword:e.detail.value
        })
    },
    tabSelect(e) {
        this.setData({
          TabCur: e.currentTarget.dataset.id,
          MainCur: e.currentTarget.dataset.id,
          VerticalNavTop: (e.currentTarget.dataset.id - 1) * 50
        })
    },
    gd(e){
        console.log(e.currentTarget.dataset.category)
        wx.navigateTo({
          url: '../gc/gc2/gc2?category='+e.currentTarget.dataset.category,
        })
    }
}
})
